using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using BLF;
using BLF.WWW_WWW.Wiki;
using Model.WWW_WWW.Wiki;

namespace Web.WebForm.WWW.Wiki
{
    public class RSS : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.ContentType = "text/xml;charset=UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;

            Pages pages = Pages.Instance;

            if (Request["Page"] != null)
            {
                PageInfo page = pages.FindPage(Request["Page"]);
                if (page == null) return;
                PageContent content = BLF.WWW_WWW.Wiki.Content.GetPageContent(page, true);
                if (Request["Discuss"] == null)
                {
                    Response.Write(RssHead);

                    Response.Write("<channel>" + BuildChannelHead(Settings.WikiTitle + " - " + content.Title, Settings.MainUrl+"wiki-" + page.Name + Settings.PageExtension, content.Title + " - " + Resources.Messages.PageUpdates));
                    Response.Write("<item>");
                    Response.Write("<title><![CDATA[" + content.Title + "]]></title>");
                    Response.Write("<link>" + Settings.MainUrl + "wiki-" + page.Name + Settings.PageExtension + "</link>");
                    Response.Write("<description><![CDATA[" + content.Title + ": " + Exchanger.ResourceExchanger.GetResource("ThePageHasBeenUpdatedBy") + " " + content.User + (content.Comment.Length > 0 ? ".<br />" + content.Comment : ".") + "]]></description>");
                    Response.Write("<pubDate>" + content.LastModified.ToUniversalTime().ToString("R") + "</pubDate>");
                    Response.Write("<guid>" + Settings.MainUrl + "wiki-" + page.Name + Settings.PageExtension + "</guid>");
                    Response.Write("</item>");
                    Response.Write("</channel>");

                    Response.Write(RssFoot);
                }
                else
                {
                    List<Message> messages = new List<Message>(Pages.Instance.GetPageMessages(page));
                    // Un-tree Messages
                    UnTreeMessages(messages, messages);
                    // Sort from newer to older
                    messages.Sort(new MessageDateTimeComparer(true));

                    Response.Write(RssHead);

                    Response.Write("<channel>" + BuildChannelHead(Settings.WikiTitle + " - " + content.Title + " - Discussion Updates", Settings.MainUrl + "wiki-" + page.Name + Settings.PageExtension + "?Discuss=1", Settings.WikiTitle + " - " + content.Title + " - Discussion Updates"));

                    //int shift;
                    for (int i = 0; i < messages.Count; i++)
                    {
                        Response.Write("<item>");
                        Response.Write("<title><![CDATA[" + messages[i].Subject + "]]></title>");
                        Response.Write("<link>" + Settings.MainUrl + "wiki-" + page.Name + Settings.PageExtension + "?Discuss=1</link>");
                        Response.Write("<description><![CDATA[" + Formatter.Format(messages[i].Body, null) + "]]></description>");
                        Response.Write("<pubDate>" + messages[i].DateTime.ToUniversalTime().ToString("R") + "</pubDate>");
                        Response.Write("<guid>" + page.Name + "." + messages[i].ID.ToString() + "</guid>");
                        Response.Write("</item>");
                    }

                    Response.Write("</channel>");

                    Response.Write(RssFoot);
                }
            }
            else
            {
                // All updates
                Response.Write(RssHead);

                Response.Write("<channel>" + BuildChannelHead(Settings.WikiTitle + " - " + Resources.Messages.PageUpdates, Settings.MainUrl, Exchanger.ResourceExchanger.GetResource("RecentPageUpdates")));

                bool useCat = false;
                string cat = "";
                if (Request["Category"] != null)
                {
                    useCat = true;
                    cat = Request["Category"];
                }

                RecentChange[] ch = RecentChanges.Instance.AllChanges;
                Array.Reverse(ch);
                //int shift;
                for (int i = 0; i < ch.Length; i++)
                {
                    PageInfo p = Pages.Instance.FindPage(ch[i].Page);
                    if (p != null && useCat)
                    {
                        CategoryInfo[] infos = Pages.Instance.GetCategoriesPerPage(p);
                        if (infos.Length == 0)
                        {
                            if (!cat.Equals("-")) continue;
                        }
                        else
                        {
                            bool found = false;
                            for (int k = 0; k < infos.Length; k++)
                            {
                                if (infos[k].Name.Equals(cat))
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) continue;
                        }
                    }
                    else if (p == null && useCat) continue;
                    Response.Write("<item>");
                    Response.Write("<title><![CDATA[" + ch[i].Title + "]]></title>");
                    if (ch[i].Change != Change.PageDeleted)
                        Response.Write("<link>" + Settings.MainUrl + "wiki-" + ch[i].Page + Settings.PageExtension + "</link>");
                    else Response.Write("<link>" + Settings.MainUrl + "</link>");
                    Response.Write("<description><![CDATA[");
                    switch (ch[i].Change)
                    {
                        case Change.PageUpdated:
                            Response.Write(Exchanger.ResourceExchanger.GetResource("ThePageHasBeenUpdatedBy"));
                            break;
                        case Change.PageDeleted:
                            Response.Write(Exchanger.ResourceExchanger.GetResource("ThePageHasBeenDeletedBy"));
                            break;
                        case Change.PageRenamed:
                            Response.Write(Exchanger.ResourceExchanger.GetResource("ThePageHasBeenRenamedBy"));
                            break;
                        case Change.PageRolledBack:
                            Response.Write(Exchanger.ResourceExchanger.GetResource("ThePageHasBeenRolledBackBy"));
                            break;
                    }
                    Response.Write(" " + ch[i].User + (ch[i].Description.Length > 0 ? ".<br />" + ch[i].Description : ".") + "]]></description>");
                    Response.Write("<pubDate>" + ch[i].DateTime.ToUniversalTime().ToString("R") + "</pubDate>");
                    Response.Write("<guid>" + Settings.MainUrl + "wiki-" + ch[i].Page + Settings.PageExtension + "</guid>");
                    Response.Write("</item>");
                }
                Response.Write("</channel>");

                Response.Write(RssFoot);
            }

        }

        private void UnTreeMessages(List<Message> root, List<Message> messages)
        {
            for (int i = 0; i < messages.Count; i++)
            {
                root.AddRange(messages[i].Replies);
                UnTreeMessages(root, messages[i].Replies);
                messages[i].Replies.Clear();
            }
        }

        private string BuildChannelHead(string title, string link, string description)
        {
            string result = "";
            result += "<title><![CDATA[" + title + "]]></title>";
            result += "<link>" + link + "</link>";
            result += "<description>" + description + "</description>";
            DateTime now = DateTime.Now;
            result += "<pubDate>" + now.ToUniversalTime().ToString("R") + "</pubDate>";
            result += "<generator>ItalkI Wiki RSS Feed Generator</generator>";
            return result;
        }

        private string RssHead
        {
            get
            {
                string head = @"<rss version=""2.0"">" + "\r\n";
                return head;
            }
        }

        private string RssFoot
        {
            get
            {
                string foot = "</rss>" + "\r\n";
                return foot;
            }
        }
    }
}
